package com.atguigu.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.EduConfig;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * ClassName: DimUtil
 * Package: com.atguigu.utils
 * Description:
 *
 * @Author Lovxy
 * @Create 2023/5/17 15:13
 * @Version 1.0
 */
public class DimUtil {
    public static JSONObject getDimInfo(Connection connection, String tableName, String id) throws Exception {

        //查询Redis
        Jedis jedis = JedisUtil.getJedis();
        String redisKey = "DIM:" + tableName.toUpperCase() + ":" + id;
        String dimInfoStr = jedis.get(redisKey);
        if (dimInfoStr != null) {
            //重置过期时间
            jedis.expire(redisKey, 24 * 3600);
            jedis.close();
            return JSON.parseObject(dimInfoStr);
        }

        //拼接SQL
        String sql = "select * from " + EduConfig.HBASE_SCHEMA + "." + tableName + " where id='" + id + "'";
        System.out.println("查询SQL为：" + sql);

        List<JSONObject> jsonObjects = JdbcUtil.queryList(connection,
                sql,
                JSONObject.class,
                false);

        //将数据写入Redis
        JSONObject dimInfo = jsonObjects.get(0);
        jedis.setex(redisKey, 24 * 3600, dimInfo.toJSONString());
        jedis.close();

        //返回结果
        return jsonObjects.get(0);
    }
}
